package com.example.security;

import com.example.dto.ApiResponse;
import com.example.utils.IpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.ConsumptionProbe;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.List;
import java.util.Collections;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    private final RateLimitConfig rateLimitConfig;
    private final ObjectMapper objectMapper;
    private final List<String> exemptedPaths;
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    
    @Autowired
    private IpUtils ipUtils;

    @Autowired
    public RateLimitInterceptor(RateLimitConfig rateLimitConfig, ObjectMapper objectMapper, @Value("${rate-limit.exempted-paths:}") List<String> exemptedPaths) {
        this.rateLimitConfig = rateLimitConfig;
        this.objectMapper = objectMapper;
        this.exemptedPaths = exemptedPaths != null ? exemptedPaths : Collections.emptyList();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        
        for (String pattern : exemptedPaths) {
            if (pathMatcher.match(pattern, requestUri)) {
                return true;
            }
        }

        String ipAddress = ipUtils.getClientIpAddress(request);
        Bucket bucket = rateLimitConfig.resolveBucket(ipAddress);
        ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1);

        if (probe.isConsumed()) {
            response.addHeader("X-Rate-Limit-Remaining", String.valueOf(probe.getRemainingTokens()));
            return true;
        } else {
            long waitForRefill = probe.getNanosToWaitForRefill() / 1_000_000_000;
            response.addHeader("X-Rate-Limit-Retry-After-Seconds", String.valueOf(waitForRefill));
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            writeErrorResponse(response, "Rate limit exceeded. Try again in " + waitForRefill + " seconds.");
            return false;
        }
    }

    private void writeErrorResponse(HttpServletResponse response, String message) throws IOException {
        ApiResponse<?> errorResponse = ApiResponse.error(message);
        response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
    }

    /**
     * @deprecated 使用IpUtils.getClientIpAddress()替代
     */
    @Deprecated
    private String getClientIP(HttpServletRequest request) {
        return ipUtils.getClientIpAddress(request);
    }
}